<template>
  <div>
    <el-switch
      v-model="draggable"
      active-text="开启拖拽"
      inactive-text="关闭拖拽"
    >
    </el-switch>
    <el-button
      type="success"
      icon="el-icon-check"
      circle
      @click="batchSave"
      v-if="draggable"
    ></el-button>
    <el-button
      type="danger"
      icon="el-icon-delete"
      circle
      @click="batchDelete"
    ></el-button>
    <el-tree
      :data="menus"
      :props="defaultProps"
      :expand-on-click-node="false"
      show-checkbox
      :default-expanded-keys="expandedKeys"
      node-key="catId"
      v-loading="dataListLoading"
      :draggable="draggable"
      :allow-drop="allowDrop"
      @node-drop="handleDrop"
      ref="menuTree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level <= 2"
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            Append
          </el-button>
          <el-button type="text" size="mini" @click="() => edit(data)">
            Edit
          </el-button>
          <el-button
            v-if="node.childNodes.length == 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >
            Delete
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog
      :title="dialogType_title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="30%"
    >
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input
            v-model="category.productUnit"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    return {
      pCids: [], // 拖拽时拖拽节点新父节点id
      draggable: false, // 控制是否开启拖拽
      updateNodes: [], // 批量排序节点
      draggingMaxLevel: 1, // 判断是否能拖拽时，拖拽节点的最大层级
      dialogType_title: "提示",
      dialogType_enum: ["edit", "add"],
      dialogType: "", // 隐藏对话框类型。 edit/add
      dataListLoading: false, // 控制页面加载时加载框显示
      dialogVisible: false, // 控制添加时表单框显示
      expandedKeys: [], // 默认展开节点
      menus: [], // 三级菜单数据
      // 添加表单数据
      category: {
        catId: null,
        name: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        productUnit: "",
        icon: "",
      },
      // 树节点信息
      defaultProps: {
        children: "childrens",
        label: "name",
      },
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    dialogType(newValue, oldValue) {
      if (newValue == this.dialogType_enum[0]) {
        this.dialogType_title = "修改此分类";
      }
      if (newValue == this.dialogType_enum[1]) {
        this.dialogType_title = "添加子菜单";
      }
    },
  },
  //方法集合
  methods: {
    // 加载三级菜单
    getMenuList() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get",
      }).then(({ data }) => {
        this.menus = this.checkResult(data) ? data.data : [];
        this.dataListLoading = false;
      });
    },
    // 批量删除
    batchDelete() {
      let checkedNodes = this.$refs.menuTree.getCheckedNodes();
      let catIds = checkedNodes.map(item => item.catId);
      console.log(catIds);
      this.$confirm(
        `确定对[${catIds}]进行[${
          catIds.length <= 1 ? "删除" : "批量删除"
        }]操作?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(catIds, false),
          }).then(({ data }) => {
            this.handleResult(data, []);
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 拖拽保存
    batchSave() {
      this.$http({
        url: this.$http.adornUrl("/product/category/update/sort"),
        method: "post",
        data: this.$http.adornData(this.updateNodes, false),
      }).then(({ data }) => {
        this.handleResult(data, this.pCids);
      });
      this.updateNodes = [];
    },
    // 拖拽功能
    handleDrop(draggingNode, dropNode, dropType, ev) {
      // 1、确定拖拽节点最新parentCId
      let pCid =
        dropType == "inner"
          ? dropNode.data.catId
          : dropNode.parent.data.catId || 0;
      this.pCids.push(pCid);
      // 2、确定拖拽节点最新顺序 + 3、确定拖拽节点最新层级
      let siblings =
        dropType == "inner" ? dropNode.childNodes : dropNode.parent.childNodes;
      for (let i = 0; i < siblings.length; i++) {
        //如果遍历的不是当前正在拖拽的节点
        if (siblings[i].data.catId != draggingNode.data.catId) {
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i });
          continue;
        }
        // 当前拖拽节点最新位置的level 不等于原始level，标明层级发生改变
        if (siblings[i].level != draggingNode.data.catLevel) {
          this.updateChildNodeLevel(siblings[i]);
        }
        this.updateNodes.push({
          catId: siblings[i].data.catId,
          sort: i,
          parentCid: pCid,
          catLevel: siblings[i].level,
        });
      }
    },
    updateChildNodeLevel(node) {
      if (node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          this.updateNodes.push({
            catId: node.childNodes[i].data.catId,
            catLevel: node.childNodes[i].level,
          });
          this.updateChildNodeLevel(node.childNodes[i]);
        }
      }
    },
    // 拖拽时判定目标节点能否被放置 (当前节点、目标节点、对应位置)
    allowDrop(draggingNode, dropNode, type) {
      // 方法一：
      // 当前拖拽的节点大于父节点，或大于等于之前/之后的节点 -- 若一级二级菜单下无子节点，依旧无法拖入到三级目录下
      //   var currLevel = draggingNode.data.catLevel;
      //   var dropLevel = dropNode.data.catLevel;
      //   return (
      //     (type == "inner" && currLevel > dropLevel) ||
      //     (type != "inner" && currLevel >= dropLevel)
      //   );

      // 方法二：
      this.draggingMaxLevel = draggingNode.level;
      // 获取当前拖动节点的最大层级（包括叶子节点）
      this.countNodeLevel(draggingNode);
      // 计算出当前拖动节点的深度，
      var deep = Math.abs(this.draggingMaxLevel - draggingNode.level) + 1;
      // （inner）判断拖拽节点深度+目标节点层级<=3 或（!inner）拖拽节点深度+目标节点的父节点层级<=3
      var level = deep + dropNode.level;
      console.log(deep, dropNode.level, level);
      return (type == "inner" && level <= 3) || (type != "inner" && level <= 4);
    },
    countNodeLevel(node) {
      var childrens = node.childNodes;
      if (childrens != null && childrens.length > 0) {
        for (let i = 0; i < childrens.length; i++) {
          if (childrens[i].level > this.draggingMaxLevel) {
            this.draggingMaxLevel = childrens[i].level;
          }
          this.countNodeLevel(childrens[i]);
        }
      }
    },
    // category 清空为默认数据
    clearCategory() {
      this.category = this.$options.data.call(this).category;
      //   this.category.catId = null;
      //   this.category.name = "";
      //   this.category.parentCid = 0;
      //   this.category.catLevel = 0;
      //   this.category.showStatus = 1;
      //   this.category.sort = 0;
      //   this.category.productUnit = "";
      //   this.category.icon = "";
    },
    // 表单提交方法
    submitData() {
      if (this.dialogType == this.dialogType_enum[0]) {
        this.editCategory();
      } else if (this.dialogType == this.dialogType_enum[1]) {
        this.addCategory();
      }
    },
    // 打开修改菜单页面
    edit(data) {
      this.clearCategory();
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get",
      }).then(({ data }) => {
        if (this.checkResult(data)) {
          //   this.category.name = data.data.name;
          //   this.category.catId = data.data.catId;
          //   this.category.parentCid = data.data.parentCid;
          //   this.category.productUnit = data.data.productUnit;
          //   this.category.icon = data.data.icon;
          Object.assign(this.category, data.data);
          this.dialogType = this.dialogType_enum[0]; // 标记为修改操作
          this.dialogVisible = true;
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    // 打开添加菜单页面
    append(data) {
      this.clearCategory();
      this.dialogType = this.dialogType_enum[1]; // 标记为添加操作
      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1;
      this.dialogVisible = true; // 开启对话框
    },
    editCategory() {
      if (!this.category.name) {
        this.$message.error("分类名不能为空！");
        return;
      }
      //   var { name, catId, productUnit, icon } = this.category;
      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "post",
        data: this.$http.adornData(this.category, false),
      }).then(({ data }) => {
        this.handleResult(data, [this.category.parentCid]);
        if (this.checkResult(data)) {
          // 关闭对话框
          this.dialogVisible = false;
        }
      });
    },
    // 添加节点
    addCategory() {
      if (!this.category.name) {
        this.$message.error("分类名不能为空！");
        return;
      }
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.category, false),
      }).then(({ data }) => {
        this.handleResult(data, [this.category.parentCid]);
        if (this.checkResult(data)) {
          // 关闭对话框
          this.dialogVisible = false;
        }
      });
    },
    // 删除节点
    remove(node, data) {
      var ids = [data.catId];
      this.$confirm(
        `确定对[${data.name}]进行[${
          ids.length <= 1 ? "删除" : "批量删除"
        }]操作?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            this.handleResult(data, [node.parent.data.catId]);
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    checkResult(data) {
      return data && data.code === 0;
    },
    handleResult(data, expandedKeys) {
      if (this.checkResult(data)) {
        this.$message({
          message: "操作成功",
          type: "success",
          duration: 1500,
          onClose: () => {
            this.getMenuList();
            this.expandedKeys = expandedKeys;
          },
        });
      } else {
        this.$message.error(data.msg);
      }
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getMenuList();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped>
</style>